package com.java202411.repository;


import com.java202411.entity.FileEntity;
import com.java202411.repository.client.FileDatabaseClient;
import com.java202411.repository.client.MinioHTTPClient;
import com.java202411.repository.table.FileTable;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.StreamSupport;

@Repository
@RequiredArgsConstructor
public class FileRepository {
    private final FileDatabaseClient fileDatabaseClient;

    public FileEntity save(FileEntity build) {
        FileTable row = FileTable.builder()
                .id(build.getId())
                .createdAt(build.getCreatedAt())
                .updatedAt(build.getUpdatedAt())
                .name(build.getName())
                .code(build.getCode())
                .contentType(build.getContentType())
                .build();

        row = fileDatabaseClient.save(row);

        return FileEntity.builder()
                .id(row.getId())
                .createdAt(row.getCreatedAt())
                .updatedAt(row.getUpdatedAt())
                .name(row.getName())
                .code(row.getCode())
                .contentType(row.getContentType())
                .build();
    }

    public List<FileEntity> findByIds(List<Long> fileIds) {
        Iterable<FileTable> rows = fileDatabaseClient.findAllById(fileIds);
        return StreamSupport.stream(rows.spliterator(), false)
                .map(row -> FileEntity.builder()
                        .id(row.getId())
                        .createdAt(row.getCreatedAt())
                        .updatedAt(row.getUpdatedAt())
                        .name(row.getName())
                        .code(row.getCode())
                        .contentType(row.getContentType())
                        .build()
                )
                .toList();
    }
}
